<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="showSearch">
        <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px" class="search-form">
          <el-form-item label="人员类型" prop="userType">
            <el-select v-model="queryParams.userType" placeholder="请选择人员类型" clearable>
              <el-option v-for="dict in user_type" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="姓名" prop="userName">
            <el-input v-model="queryParams.userName" placeholder="请输入姓名" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="通行状态" prop="passType">
            <el-select v-model="queryParams.passType" placeholder="请选择通行状态" clearable>
              <el-option v-for="dict in pass_type" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="闸机" prop="deviceId">
            <!-- <el-input v-model="queryParams.deviceId" placeholder="请输入设备ID" clearable style="width: 240px" @keyup.enter="handleQuery" /> -->
            <el-select v-model="queryParams.deviceId" placeholder="请选择关联闸机" style="width:100%" filterable clearable>
              <el-option v-for="dict in zjDeviceList" :key="dict.id" :label="dict.name" :value="dict.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="方向" prop="inOutMark">
            <el-select v-model="queryParams.inOutMark" placeholder="请选择方向" clearable>
              <el-option v-for="dict in in_out_mark" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="安装区域" prop="area">
            <el-select v-model="queryParams.passType" placeholder="请选择安装区域" clearable>
              <el-option v-for="dict in device_area" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="识别时间" style="width: 440px">
            <el-date-picker
              v-model="dateRangeClockingTime"
              value-format="YYYY-MM-DD HH:mm:ss"
              type="datetimerange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
            />
          </el-form-item>
          <el-form-item>
            <el-button-group>
              <el-button @click="timeClick(1)">最近1小时</el-button>
              <el-button @click="timeClick(2)">最近1天</el-button>
              <el-button @click="timeClick(3)">最近3天</el-button>
              <el-button @click="timeClick(4)">最近7天</el-button>
            </el-button-group>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <!-- <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['device:deviceClockingRecord:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['device:deviceClockingRecord:edit']"
              >修改</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="Delete"
              :disabled="multiple"
              @click="handleDelete()"
              v-hasPermi="['device:deviceClockingRecord:remove']"
              >删除</el-button
            >
          </el-col> -->
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['device:deviceClockingRecord:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table
        v-loading="loading"
        :data="deviceClockingRecordList"
        @selection-change="handleSelectionChange"
        @row-dblclick="(row)=>handleDetail(row)"
      >
        <!-- <el-table-column type="selection" width="55" align="center" /> -->
        <!-- <el-table-column label="ID" align="center" prop="id" v-if="true" /> -->
        <el-table-column label="姓名" align="center" prop="userName" />
        <el-table-column label="性别" align="center" prop="gender">
          <template #default="scope">
            <dict-tag :options="student_sex" :value="scope.row.gender" />
          </template>
        </el-table-column>
        <el-table-column label="人员类型" align="center" prop="userType">
          <template #default="scope">
            <dict-tag :options="user_type" :value="scope.row.userType" />
          </template>
        </el-table-column>
        <el-table-column label="班级/部门" align="center" prop="className" />
        <el-table-column label="识别时间" align="center" prop="clockingTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.clockingTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="通行状态" align="center" prop="passType">
          <template #default="scope">
            <dict-tag :options="pass_type" :value="scope.row.passType" />
          </template>
        </el-table-column>
        <el-table-column label="设备名称" align="center" prop="deviceName" />
        <el-table-column label="方向" align="center" prop="inOutMark">
          <template #default="scope">
            <dict-tag :options="in_out_mark" :value="scope.row.inOutMark" />
          </template>
        </el-table-column>
        <el-table-column label="安装区域" align="center" prop="area">
          <template #default="scope">
            <dict-tag :options="device_area" :value="scope.row.area" />
          </template>
        </el-table-column>
        <el-table-column label="抓拍图" align="center" prop="capturePhoto">
          <template #default="scope">
            <ImagePreview
              v-if="scope.row.capturePhoto"
              :width="100"
              :height="100"
              :src="scope.row.capturePhoto"
              :preview-src-list="[scope.row.frameUrl||scope.row.capturePhoto]"
            />
          </template>
        </el-table-column>
        <el-table-column label="人脸图" align="center" prop="facePhoto">
          <template #default="scope">
            <ImagePreview
              v-if="scope.row.facePhoto"
              :width="100"
              :height="100"
              :src="scope.row.facePhoto"
              :preview-src-list="[scope.row.facePhoto]"
            />
          </template>
        </el-table-column>
        <el-table-column label="比对分值" align="center" prop="score">
          <template #default="scope">
            <span>{{ scope.row.score+"%" }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="详情" placement="top">
              <el-button
                link
                type="primary"
                icon="View"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['device:deviceClockingRecord:edit']"
              ></el-button>
            </el-tooltip>
            <!-- <el-tooltip content="删除" placement="top">
              <el-button
                link
                type="primary"
                icon="Delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['device:deviceClockingRecord:remove']"
              ></el-button>
            </el-tooltip> -->
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改设备打卡记录对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="740px" append-to-body>
      <el-form ref="deviceClockingRecordFormRef" :model="form" :rules="rules" label-width="80px" :inline="true" class="add-form" disabled>
        <!-- <el-form-item label="用户ID" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入用户ID" />
        </el-form-item> -->
        <el-form-item label="姓名" prop="userName">
          <el-input v-model="form.userName" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="人员类型" prop="userType">
          <el-select v-model="form.userType" placeholder="请选择人员类型">
            <el-option v-for="dict in user_type" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="班级/部门" prop="className">
          <el-input v-model="form.className" placeholder="请输入班级/部门" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-input v-model="form.gender" placeholder="请输入性别" />
        </el-form-item>
        <el-form-item label="识别时间" prop="clockingTime">
          <el-date-picker clearable v-model="form.clockingTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择识别时间">
          </el-date-picker>
        </el-form-item>
        <!-- <el-form-item label="打开类型：1刷卡、2刷脸" prop="clockType">
          <el-select v-model="form.clockType" placeholder="请选择打开类型：1刷卡、2刷脸">
            <el-option v-for="dict in sg_punch_type" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="通行状态" prop="passType">
          <el-select v-model="form.passType" placeholder="请选择通行状态">
            <el-option v-for="dict in pass_type" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="设备ID" prop="deviceId">
          <el-input v-model="form.deviceId" placeholder="请输入设备ID" />
        </el-form-item> -->
        <el-form-item label="设备名称" prop="deviceName">
          <el-input v-model="form.deviceName" placeholder="请输入设备名称" />
        </el-form-item>
        <!-- <el-form-item label="设备系列" prop="deviceSeries">
          <el-input v-model="form.deviceSeries" placeholder="请输入设备系列" />
        </el-form-item> -->
        <el-form-item label="方向" prop="inOutMark">
          <el-select v-model="form.inOutMark" placeholder="请选择方向">
            <el-option v-for="dict in in_out_mark" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="安装区域" prop="area">
          <el-select v-model="form.area" placeholder="请选择安装区域">
            <el-option v-for="dict in device_area" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="位置" prop="location">
          <el-input v-model="form.location" type="textarea" placeholder="请输入内容" />
        </el-form-item> -->
        <el-form-item label="比对分值" prop="score">
          <el-input v-model="form.score" placeholder="请输入比对分值" />
        </el-form-item>
        <!-- <el-form-item label="活体分数" prop="livenessScore">
          <el-input v-model="form.livenessScore" placeholder="请输入活体分数" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
        <el-form-item label="人员ID(第三方系统)" prop="personId">
          <el-input v-model="form.personId" placeholder="请输入人员ID(第三方系统)" />
        </el-form-item>
        <el-form-item label="本条识别记录ID" prop="recordId">
          <el-input v-model="form.recordId" placeholder="请输入本条识别记录ID" />
        </el-form-item> -->
        <el-form-item label="抓拍图" prop="capturePhoto">
          <ImagePreview :width="100" :height="100" :src="form.capturePhoto" :preview-src-list="[form.capturePhoto]" />
        </el-form-item>
        <el-form-item label="人脸图" prop="facePhoto">
          <ImagePreview v-if="form.facePhoto" :width="100" :height="100" :src="form.facePhoto" :preview-src-list="[form.facePhoto]" />
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup name="DeviceClockingRecord" lang="ts">
import {
  listDeviceClockingRecord,
  getDeviceClockingRecord,
  delDeviceClockingRecord,
  addDeviceClockingRecord,
  updateDeviceClockingRecord
} from '@/api/device/deviceClockingRecord';
import { listDeviceInfo } from '@/api/device/deviceInfo';
import { DeviceInfoQuery } from '@/api/device/deviceInfo/types';
import { DeviceClockingRecordVO, DeviceClockingRecordQuery, DeviceClockingRecordForm } from '@/api/device/deviceClockingRecord/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { pass_type, sg_punch_type, user_type, in_out_mark, student_sex, device_area } = toRefs<any>(
  proxy?.useDict('pass_type', 'sg_punch_type', 'user_type', 'in_out_mark', 'student_sex', 'device_area')
);

const deviceClockingRecordList = ref<DeviceClockingRecordVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const dateRangeClockingTime = ref<[DateModelType, DateModelType]>(['', '']);

const queryFormRef = ref<ElFormInstance>();
const deviceClockingRecordFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: DeviceClockingRecordForm = {
  id: undefined,
  userId: undefined,
  userType: undefined,
  userName: undefined,
  className: undefined,
  gender: undefined,
  leaveId: undefined,
  leaveType: undefined,
  clockingTime: undefined,
  clockType: undefined,
  passType: undefined,
  deviceId: undefined,
  deviceType: undefined,
  deviceName: undefined,
  deviceSeries: undefined,
  inOutMark: undefined,
  area: undefined,
  location: undefined,
  capturePhoto: undefined,
  facePhoto: undefined,
  frameUrl: undefined,
  score: undefined,
  livenessType: undefined,
  livenessScore: undefined,
  remark: undefined,
  personId: undefined,
  recordId: undefined
};
const data = reactive<PageData<DeviceClockingRecordForm, DeviceClockingRecordQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userType: undefined,
    userName: undefined,
    passType: undefined,
    deviceId: undefined,
    deviceType: 0,
    inOutMark: undefined,
    area: undefined,
    params: {
      clockingTime: undefined
    }
  },
  rules: {
    id: [{ required: true, message: 'ID不能为空', trigger: 'blur' }],
    userId: [{ required: true, message: '用户ID不能为空', trigger: 'blur' }],
    userType: [{ required: true, message: '人员类型不能为空', trigger: 'change' }],
    userName: [{ required: true, message: '姓名不能为空', trigger: 'blur' }],
    className: [{ required: true, message: '班级/部门不能为空', trigger: 'blur' }],
    gender: [{ required: true, message: '性别不能为空', trigger: 'blur' }],
    leaveId: [{ required: true, message: '请假ID不能为空', trigger: 'blur' }],
    leaveType: [{ required: true, message: '请假类型 0-事假 1-病假 2-公假不能为空', trigger: 'change' }],
    clockingTime: [{ required: true, message: '识别时间不能为空', trigger: 'blur' }],
    clockType: [{ required: true, message: '打开类型：1刷卡、2刷脸不能为空', trigger: 'change' }],
    passType: [{ required: true, message: '通行状态不能为空', trigger: 'change' }],
    deviceId: [{ required: true, message: '设备ID不能为空', trigger: 'blur' }],
    deviceType: [{ required: true, message: '设备类型不能为空', trigger: 'change' }],
    deviceName: [{ required: true, message: '设备名称不能为空', trigger: 'blur' }],
    inOutMark: [{ required: true, message: '方向不能为空', trigger: 'change' }],
    area: [{ required: true, message: '安装区域不能为空', trigger: 'blur' }],
    capturePhoto: [{ required: true, message: '抓拍图不能为空', trigger: 'blur' }],
    facePhoto: [{ required: true, message: '人脸图不能为空', trigger: 'blur' }],
    score: [{ required: true, message: '比对分值不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询设备打卡记录列表 */
const getList = async () => {
  loading.value = true;
  queryParams.value.params = {};
  proxy?.addDateRange(queryParams.value, dateRangeClockingTime.value, 'ClockingTime');
  const res = await listDeviceClockingRecord(queryParams.value);
  deviceClockingRecordList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  deviceClockingRecordFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  dateRangeClockingTime.value = ['', ''];
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: DeviceClockingRecordVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加设备打卡记录';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: DeviceClockingRecordVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getDeviceClockingRecord(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改设备打卡记录';
};

/** 提交按钮 */
const submitForm = () => {
  deviceClockingRecordFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateDeviceClockingRecord(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addDeviceClockingRecord(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('修改成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: DeviceClockingRecordVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除设备打卡记录编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delDeviceClockingRecord(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'device/deviceClockingRecord/export',
    {
      ...queryParams.value
    },
    `deviceClockingRecord_${new Date().getTime()}.xlsx`
  );
};

const timeClick = (type: number) => {
  let startTime = new Date();
  let endTime = new Date();
  if (type == 1) {
    startTime.setHours(startTime.getHours() - 1);
  } else if (type == 2) {
    startTime.setDate(startTime.getDate() - 1);
  } else if (type == 3) {
    startTime.setDate(startTime.getDate() - 3);
  } else if (type == 4) {
    startTime.setDate(startTime.getDate() - 7);
  }
  dateRangeClockingTime.value = [proxy?.parseTime(startTime, '{y}-{m}-{d} {h}:{i}:{s}'), proxy?.parseTime(endTime, '{y}-{m}-{d} {h}:{i}:{s}')];
};
const zjDeviceList = ref<any>([]);
const deviceQueryParams = reactive<DeviceInfoQuery>({
  pageNum: 1,
  pageSize: 10000,
  type: 0,
  status: 1
});
const getDeviceInfoList = async () => {
  const res = await listDeviceInfo(deviceQueryParams);
  return res.rows;
};

onMounted(() => {
  getList();
  getDeviceInfoList().then((res) => {
    zjDeviceList.value = res;
  });
});
</script>
